<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax基础</title>
</head>

<body>
    <button id="btn">点击发送请求</button>
    <div id="result">

    </div>
    <script>
        const btn = document.getElementById('btn')
        const result = document.getElementById('result')
        btn.addEventListener('click', async ()=> {
            let res = await ajax('GET', 'http://127.0.0.1:8000/server?a=1&b=2&c=3')
            console.log(res);
            result.innerHTML = res.name
        })
        async function ajax(method, url) {
            return new Promise((resolve, reject) => {
                //创建对象
                const xhr = new XMLHttpRequest();
                xhr.responseType = 'json'
                //超时设置 2s
                xhr.timeout = 2000
                //超时回调
                xhr.ontimeout = function () {
                    alert("网络异常，请稍后重试")
                }
                //网络异常
                xhr.onerror = function () {
                    alert("你的网络似乎出现了一些问题")
                }
                //初始化
                // xhr.open('GET', 'http://127.0.0.1:8000/server?a=1&b=2&c=3');
                // xhr.open('POST', 'http://127.0.0.1:8000/server')
                // xhr.open('POST', 'http://127.0.0.1:8000/delay')
                xhr.open(method, url)
                //设置请求头
                //设置请求体类型
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
                //自定义的头，浏览器有安全机制
                xhr.setRequestHeader('name', '123')
                //发送
                xhr.send('a=1&b=2&c=3');
                //处理响应结果
                xhr.onreadystatechange = function () {
                    // 0 1 2 3 4 服务端返回了所有结果
                    if (xhr.readyState == 4) {
                        //  判断状态码 200 404 403 401 500
                        if (xhr.status >= 200 && xhr.status < 300) {
                            //处理结果
                            console.log(xhr.status);//状态码
                            console.log(xhr.statusText);//状态字符串
                            console.log(xhr.getAllResponseHeaders());//响应头
                            //控制台输出响应体
                            console.log(xhr.response);
                            //手动转换
                            // result.innerHTML = JSON.parse(xhr.response).name
                            //自动转换
                            // result.innerHTML = xhr.response.name
                            resolve(xhr.response)
                        } else {
                            //输出状态码
                            console.log(xhr.status);
                            reject(xhr.status)
                        }
                    }
                }
            })
        }
    </script>
</body>

</html>